//
//  WmcMediaBrowseVideoPreviewCell.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/7/12.
//

import AVFoundation
import AVKit
import UIKit
import YPBedrock

class WmcMediaBrowseVideoPreviewCell: WmcBaseCollectionCell {
    // Lifecycle

    deinit {
        videoPlayerView.player.stop()
        videoPlayerView.player.destroy()
    }

    // Internal

    lazy var videoPlayerView: WmcVideoPlayerView = {
        let view = WmcVideoPlayerView()
        view.player.isReadyToPlay = false
        return view
    }()
    
    func play() {
        videoPlayerView.player.play()
    }
    
    func pause() {
        videoPlayerView.player.pause()
    }

    func resetSubViewStatusWhenCellStartDisplay(index: Int, currentIndex: Int) {
        videoPlayerView.player.pause()
    }

    func resetSubViewStatusWhenCellEndDisplay(index: Int, currentIndex: Int) {
        videoPlayerView.player.pause()
    }

    override func makeUI() {
        addSubview(videoPlayerView)
        videoPlayerView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    func configVideo(_ video: WmcVideo) {
        video.loadAVAsset { [weak self] avAsset in
            guard let weakSelf = self else { return }

            weakSelf.videoPlayerView.player.removeAllTask()

            weakSelf.videoPlayerView.bottomView.totalTime = 0
            weakSelf.videoPlayerView.bottomView.setProgress(currentTime: 0)

            if let url = video.url {
                let urlAsset = AVURLAsset(url: url, options: [
                    AVURLAssetPreferPreciseDurationAndTimingKey: true,
                ])
                urlAsset.loadValuesAsynchronously(forKeys: ["duration"]) {
                    let status = urlAsset.statusOfValue(forKey: "duration", error: nil)
                    switch status {
                    case .loaded:
                        let second = urlAsset.duration.seconds
                        DispatchQueue.main.async {
                            weakSelf.videoPlayerView.bottomView.totalTime = second
                            weakSelf.videoPlayerView.bottomView.setProgress(currentTime: 0)
                        }
                    default: break
                    }
                }
            }

            weakSelf.videoPlayerView.player.appendTaskWith(avAsset: avAsset)
            // 加载第一个
            weakSelf.videoPlayerView.player.loadFirstTask()
            // 设置单曲循环
            weakSelf.videoPlayerView.player.setPlayMode(.singleCycle)
        }
    }
}
